package zhanglu.family.socket.demo.otherdemo.clinet;

import zhanglu.family.socket.bean.syncbean.SyncMsgBean;
import zhanglu.family.socket.textline.factory.INetSocketFactory;
import zhanglu.family.socket.textline.factory.impl.NetSocketFactory;
import zhanglu.family.socket.textline.syncclient.SyncClientHandler;
import zhanglu.family.socket.textline.syncclient.SyncTcpClient;

/**
 * @author zhanglu
 * @date 2017年4月1日
 */
public class ClientManager {

    private INetSocketFactory factory = new NetSocketFactory(); // 获取实例工厂

    private ClientManager() {
    }

    private static ClientManager manager = null;

    public static ClientManager getInstance() {
        if (manager == null) {
            manager = new ClientManager();
        }
        return manager;
    }

    /**
     * 同步发送消息(短连接)
     * 
     * 同步消息因为发送后直接拿数据，多数可以作为短连接使用，这个方法是短连接发送同步数据
     * 
     * @param targetSession
     *            目标人
     * @param secondTimeout
     *            超时时间秒
     * @param bean
     *            消息文本
     * @return
     */
    public SyncMsgBean send(Object bean, int secondTimeout) {

        SyncTcpClient client = factory.getSyncTcpClient("127.0.0.1", 8888);
        try {
            client.startClient(new SyncClientHandler(client));
        } catch (Exception e) {
            e.printStackTrace();
        }

        SyncMsgBean resultMsg = client.send(bean, secondTimeout);

        client.dispose();

        return resultMsg;
    }
}
